import express, { Request, Response } from "express";
import AppDataSource from "../../data-source";
import { User } from "../../entity/many_to_one/user.entity";
import { Photo } from "../../entity/many_to_one/photo.entity";

const router = express.Router();

/**
 * @swagger
 * /api/manytoone/users:
 *   get:
 *     summary: 获取所有用户
 *     description: 获取所有用户的详细信息，包括关联的照片。
 *     tags:
 *       - Many_To_One
 *     responses:
 *       200:
 *         description: 成功获取所有用户。
 *         content:
 *           application/json:
 *             schema:
 *               type: array
 *               items:
 *                 $ref: '#/components/schemas/many_to_one_user'
 */
router.get("/manytoone/users", async (req: Request, res: Response) => {
  const users = await AppDataSource.getRepository(User).find({
    relations: { photos: true },
  });
  res.json(users);
});

/**
 * @swagger
 * /api/manytoone/users/{id}:
 *   get:
 *     summary: 获取指定用户的详细信息
 *     description: 获取指定用户的详细信息，包括关联的照片。
 *     tags:
 *       - Many_To_One
 *     parameters:
 *       - name: id
 *         in: path
 *         description: 用户ID
 *         required: true
 *         schema:
 *           type: integer
 *     responses:
 *       200:
 *         description: 成功获取用户。
 *         content:
 *           application/json:
 *             schema:
 *               $ref: '#/components/schemas/many_to_one_user'
 *       404:
 *         description: 用户未找到。
 */
router.get("/manytoone/users/:id", async (req: Request, res: Response) => {
  const results = await AppDataSource.getRepository(User).findOne({
    where: { id: Number(req.params.id) },
    relations: { photos: true },
  });
  if (!results) {
    res.status(404).send({ message: "用户未找到" });
    return;
  }
  res.send(results);
});

/**
 * @swagger
 * /api/manytoone/users:
 *   post:
 *     summary: 创建新用户
 *     description: 创建一个新用户，并可同时创建关联的照片。
 *     tags:
 *       - Many_To_One
 *     requestBody:
 *       required: true
 *       content:
 *         application/json:
 *           schema:
 *             type: object
 *             properties:
 *               name:
 *                 type: string
 *                 description: 用户名称
 *               photos:
 *                 type: array
 *                 items:
 *                   type: object
 *                   properties:
 *                     url:
 *                       type: string
 *                       description: 照片URL
 *                 example:
 *                   - url: "http://example.com/photo1.jpg"
 *                   - url: "http://example.com/photo2.jpg"
 *                   - url: "http://example.com/photo3.jpg"
 *     responses:
 *       201:
 *         description: 成功创建用户。
 *         content:
 *           application/json:
 *             schema:
 *               $ref: '#/components/schemas/many_to_one_user'
 *       500:
 *         description: 内部服务器错误。
 */
router.post("/manytoone/users", async (req: Request, res: Response) => {
  try {
    const userRepository = AppDataSource.getRepository(User);
    const photoRepository = AppDataSource.getRepository(Photo);

    const body = req.body;
    const user = new User();
    user.name = body.name;
    const photoList = [];

    if (body.photos && Array.isArray(body.photos)) {
      for (let i = 0; i < body.photos.length; i++) {
        const item = body.photos[i];
        const photo = new Photo();
        photo.url = item.url;
        await photoRepository.save(photo);
        photoList.push(photo);
      }
    }
    if (photoList.length) {
      user.photos = photoList;
    }
    await userRepository.save(user);
    res.status(201).send(user);
  } catch (error) {
    console.error("创建用户时出错:", error);
    res.status(500).send({ message: "内部服务器错误" });
  }
});

/**
 * @swagger
 * /api/manytoone/users/{id}:
 *   put:
 *     summary: 更新指定用户
 *     description: 更新指定用户的详细信息，并可同时更新关联的照片。
 *     tags:
 *       - Many_To_One
 *     parameters:
 *       - name: id
 *         in: path
 *         description: 用户ID
 *         required: true
 *         schema:
 *           type: integer
 *     requestBody:
 *       required: true
 *       content:
 *         application/json:
 *           schema:
 *             type: object
 *             properties:
 *               name:
 *                 type: string
 *                 description: 用户名称
 *               photos:
 *                 type: array
 *                 items:
 *                   type: object
 *                   properties:
 *                     url:
 *                       type: string
 *                       description: 照片URL
 *                 example:
 *                   - url: "http://example.com/photo1.jpg"
 *                   - url: "http://example.com/photo2.jpg"
 *                   - url: "http://example.com/photo3.jpg"
 *     responses:
 *       200:
 *         description: 成功更新用户。
 *         content:
 *           application/json:
 *             schema:
 *               $ref: '#/components/schemas/many_to_one_user'
 *       404:
 *         description: 用户未找到。
 *       500:
 *         description: 内部服务器错误。
 */
router.put("/manytoone/users/:id", async (req: Request, res: Response) => {
  try {
    const user = await AppDataSource.getRepository(User).findOne({
      where: { id: Number(req.params.id) },
      relations: { photos: true },
    });
    if (!user) {
      res.status(404).send({ message: "用户未找到" });
      return;
    }
    const photoList = [];
    const body = req.body;
    if (body.photos && Array.isArray(body.photos)) {
      for (let i = 0; i < body.photos.length; i++) {
        const item = body.photos[i];
        const photo = new Photo();
        photo.url = item.url;
        await AppDataSource.getRepository(Photo).save(photo);
        photoList.push(photo);
      }
    }

    if (photoList.length) {
      user.photos = photoList;
    }

    const results = await AppDataSource.getRepository(User).save(user);
    res.send(results);
  } catch (error) {
    console.error("更新用户时出错:", error);
    res.status(500).send({ message: "内部服务器错误" });
  }
});

/**
 * @swagger
 * /api/manytoone/users/{id}:
 *   delete:
 *     summary: 删除指定用户
 *     description: 删除指定用户及其关联的照片。
 *     tags:
 *       - Many_To_One
 *     parameters:
 *       - name: id
 *         in: path
 *         description: 用户ID
 *         required: true
 *         schema:
 *           type: integer
 *     responses:
 *       200:
 *         description: 成功删除用户。
 *         content:
 *           application/json:
 *             schema:
 *               type: object
 *               properties:
 *                 affected:
 *                   type: integer
 *                   description: 影响的行数
 *       404:
 *         description: 用户未找到。
 */
router.delete("/manytoone/users/:id", async (req: Request, res: Response) => {
  try {
    const userId = Number(req.params.id);

    // 查找用户
    const user = await AppDataSource.getRepository(User).findOne({
      where: { id: userId },
      relations: { photos: true },
    });

    if (!user) {
      res.status(404).send({ message: "用户未找到" });
      return;
    }

    // 删除所有关联的照片
    const photoIds = user.photos.map((photo) => photo.id);
    await AppDataSource.getRepository(Photo).delete(photoIds);

    // 删除用户
    const results = await AppDataSource.getRepository(User).delete(userId);

    if (results.affected === 0) {
      res.status(404).send({ message: "用户未找到" });
      return;
    }

    res.status(200).send({ message: "用户删除成功" });
  } catch (error) {
    console.error("删除用户时出错:", error);
    res.status(500).send({ message: "内部服务器错误" });
  }
});

export default router;
